<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\model\AboutUsModel;
use app\model\BookChaptersModel;
use app\model\BookContentsModel;
use app\model\BooksModel;
use app\model\RedisModel;
use think\App;
use think\facade\Db;

class BookChapters extends Base {

    private $model;

    private $bookContentsModel;

    public $cacheKey="chapter:id:";

    public $contentCacheKey="chapter:content:id";

    private $req;

    private $aid;



    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->model = new BookChaptersModel();

        $this->bookContentsModel = new BookContentsModel();

        $this->page = isset($this->req['page']) ? $this->req['page'] : 1;

        $this->limit = isset($this->req['limit']) ? $this->req['limit'] : 999999;

        $this->aid = $this->isLogin();
    }



    /*
     * 获取店铺列表
     * */
    public function getBookChaptersList(){

        if(!isset($this->req['book_id']) || empty($this->req['book_id'])){
            return $this->fail("请选择要处理的书籍");
        }

        $where =[];
        $where[] = ["book_id","=",$this->req['book_id']];

        $info = $this->model->getList($where);

        return $this->succ($info);

    }


    public function getChaptersContent(){

        if(!isset($this->req['chapter_id']) || empty($this->req['chapter_id'])){
            return $this->fail("chapter_id 不能为空");
        }

        $data = $this->model->getInfo($this->req['chapter_id']);
        if(!empty($data)){
            $info = $this->bookContentsModel->getChapterInfo($this->req['chapter_id']);
            $data["chapter_content"] = $info["chapter_content"];
        }

        return $this->succ($data);

    }


    /*
    * 新增/删除/修改
    * */
    public function add()
    {

        if(!isset($this->req['book_id']) || empty($this->req['book_id'])){
            return $this->fail("书籍id不能为空");
        }

        if(!isset($this->req['chapter_title']) || empty($this->req['chapter_title'])){
            return $this->fail("标题不能为空");
        }

        if(!isset($this->req['chapter_content']) || empty($this->req['chapter_content'])){
          //  return $this->fail("章节内容不能为空");
        }

        if(isset($this->req['parent_id']) && !empty($this->req['parent_id'])){
            $where =[];
            $where[] = ["book_id","=",$this->req['book_id']];
            $where[] = ["chapter_id","=",($this->req['parent_id'])];
            if($this->model->getTotal($where) == 0){
                return $this->fail("父级章节不存在，请核实");
            }
        }

        if($this->model->getTotal([
                "book_id"=>$this->req['book_id'],
                "parent_id"=>$this->req['parent_id'],
                "chapter_title"=>($this->req['chapter_title'])
            ]) > 0){
            return $this->fail("同级已存在相同标题的章节");
        }



        Db::startTrans();
        $chapter_id = $this->model->addOne([
            "parent_id"=>($this->req['parent_id']),
            "book_id"=>($this->req['book_id']) ,
            "chapter_title"=>($this->req['chapter_title']),
            "chapter_desc"=>($this->req['chapter_desc']),
            "is_listen"=>isset($this->req['is_listen']) ? $this->req['is_listen'] : 0,
            "listen_url"=>isset($this->req['listen_url']) ? $this->req['listen_url'] : "",
            "created_by"=>$this->aid,
            "updated_at"=>date("Y-m-d H:i:s")
        ]);

        if(!empty($this->req['chapter_content'])){
            $res2 = $this->bookContentsModel->addOne([
                "chapter_id"=>$chapter_id,
                "chapter_content"=>($this->req['chapter_content'])
            ]);
        }else{
            $res2 = true;
        }


        if($chapter_id && $res2){
            Db::commit();
            return $this->succ();
        }else{
            Db::rollback();
            return $this->fail();
        }
    }



    /*
   * 新增/删除/修改
   * */
    public function edit()
    {

        if(!isset($this->req['chapter_id']) || empty($this->req['chapter_id'])){
            return $this->fail("请选择要处理的章节");
        }

        if(!isset($this->req['book_id']) || empty($this->req['book_id'])){
            return $this->fail("书籍id不能为空");
        }

        if(!isset($this->req['chapter_title']) || empty($this->req['chapter_title'])){
            return $this->fail("标题不能为空");
        }

        if(!isset($this->req['chapter_content']) || empty($this->req['chapter_content'])){
           // return $this->fail("章节内容不能为空");
        }

        if(isset($this->req['parent_id']) && !empty($this->req['parent_id'])){
            $where =[];
            $where[] = ["book_id","=",$this->req['book_id']];
            $where[] = ["chapter_id","=",($this->req['parent_id'])];
            if($this->model->getTotal($where) == 0){
                return $this->fail("父级章节不存在，请核实");
            }
        }

        $where =[];
        $where[] = ["book_id","=",$this->req['book_id']];
        $where[] = ["chapter_id","<>",$this->req['chapter_id']];
        $where[] = ["parent_id","=",$this->req['parent_id']];
        $where[] = ["chapter_title","=",($this->req['chapter_title'])];
        if($this->model->getTotal($where) > 0){
            return $this->fail("同级已存在相同标题的章节");
        }

        Db::startTrans();
        $res = $this->model->updateAll(["chapter_id"=>$this->req['chapter_id']],[
            "parent_id"=>($this->req['parent_id']),
            "book_id"=>($this->req['book_id']) ,
            "chapter_title"=>($this->req['chapter_title']),
            "chapter_desc"=>($this->req['chapter_desc']),
            "created_by"=>$this->aid,
            "is_listen"=>isset($this->req['is_listen']) ? $this->req['is_listen'] : 0,
            "listen_url"=>isset($this->req['listen_url']) ? $this->req['listen_url'] : "",
            "updated_at"=>date("Y-m-d H:i:s"),
        ]);

        if(!empty($this->req['chapter_content'])){
            if(empty($this->bookContentsModel->getChapterInfo($this->req['chapter_id']))){
                $res2 = $this->bookContentsModel->addOne([
                    "chapter_id"=>$this->req['chapter_id'],
                    "chapter_content"=>($this->req['chapter_content'])
                ]);
            }else{
                $res2 = $this->bookContentsModel->updateAll(["chapter_id"=>$this->req['chapter_id']],[
                    "chapter_content"=>($this->req['chapter_content']),
                    "updated_at"=>date("Y-m-d H:i:s"),
                ]);
            }
        }else{
            $this->bookContentsModel->delAll(["chapter_id"=>$this->req['chapter_id']]);
            $res2 = true;
        }


        if($res || $res2){
            Db::commit();
            $this->delCache($this->req['chapter_id']);
            return $this->succ();
        }else{
            Db::rollback();
            return $this->fail();
        }
    }




    /*
     * 删除书籍
     * */
    public function del()
    {

        if(!isset($this->req['chapter_id']) || empty($this->req['chapter_id'])){
            return $this->fail("请选择要处理的书籍");
        }

        $res1 = $this->model->where(["chapter_id"=>$this->req['chapter_id']])->delete();

        $res2 = $this->model->where(["parent_id"=>$this->req['chapter_id']])->delete();

        $res3 = $this->bookContentsModel->where(["chapter_id"=>$this->req['chapter_id']])->delete();

        if($res1){

            $this->delCache($this->req['chapter_id']);

            return $this->succ();
        }else{
            return $this->fail();
        }
    }




    public function delCache($id)
    {
        $redisModel = new RedisModel();

        $redisModel ->delete($this->contentCacheKey.$id);

        return $redisModel->delete($this->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();
        $redisModel->deleteAll($this->contentCacheKey);
        return $redisModel->deleteAll($this->cacheKey);
    }
}
